package com.talkyun.openx;


import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class OpenxSetting {

    public static final String OPENX_WRITE_NULL = "openx.write.null";

    public static final boolean OPENX_CLIENT_ASYNC;
    public static final boolean OPENX_CLIENT_KEEP_ALIVE;

    static {
        OPENX_CLIENT_ASYNC = getEnvSetting("openx.client.async", false);
        OPENX_CLIENT_KEEP_ALIVE = getEnvSetting("openx.client.keep-alive", true);
    }

    private static boolean getEnvSetting(String key, boolean defaultValue) {
        Properties props = System.getProperties();
        Enumeration<?> enu = props.propertyNames();
        while (enu.hasMoreElements()) {
            String tmpKey = enu.nextElement().toString();
            if (tmpKey.equalsIgnoreCase(key)) {
                return Boolean.parseBoolean(props.getProperty(tmpKey));
            }
        }
        return defaultValue;
    }

    private static ThreadLocal<Map<String, Object>> local = new ThreadLocal<Map<String, Object>>() {
        @Override
        protected Map<String, Object> initialValue() {
            return new HashMap<>();
        }
    };

    public static void setTlSetting(String feature, String setting) {
        Map<String, Object> settings = local.get();
        settings.put(feature, setting);
    }

    public static Object getTlSetting(String feature) {
        return local.get().get(feature);
    }

    public static boolean getTlSettingAsBoolean(String feature) {
        Map<String, Object> settings = local.get();
        Object setting = settings.get(feature);

        if (setting == null) {
            return false;
        }
        if (setting instanceof Boolean) {
            return (Boolean) setting;
        }
        return Boolean.parseBoolean(setting.toString());
    }
}